﻿#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2008 ZHENG Zhong <heavyzheng nospam-at gmail D0T com>
# - http://www.zhengzhong.net/
# - http://blog.zhengzhong.net/
#
# Created on 2008-12-19.
# $Id: models.py 306 2008-12-19 18:56:59Z heavyzheng $
#

import logging

from google.appengine.ext import db

MODELS_REVISION = "$Revision: 306 $"


class MyFile(db.Model):
    """This model class represents an uploaded file. The key_name of the model is the file name,
    which is stored as a Unicode string (with str values converted as ASCII text). The requirements
    on key_name are:
    1) A key_name must not start with a number, and must not be of the form __*__ (required by
       Google Datastore).
    2) Some names are reserved: tag, upload, admin.
    """
    
    PUBLIC_STATUS  = 1
    PRIVATE_STATUS = 2
    
    name        = db.StringProperty(required=True)
    desc        = db.StringProperty()
    mime_type   = db.StringProperty(required=True)
    data        = db.BlobProperty(required=True)
    md5         = db.StringProperty()
    size        = db.StringProperty()
    owner       = db.UserProperty()
    upload_date = db.DateTimeProperty(auto_now_add=True)
    tags        = db.StringListProperty(default=[])
    downloads   = db.IntegerProperty(default=0)
    status      = db.IntegerProperty(default=PUBLIC_STATUS)

    def is_image(self):
        return self.mime_type.startswith("image/")
    
    def tags_str(self):
        return " ".join(self.tags)
    
    def put(self):
        # Remove duplicated tags.
        self.tags = list(set(self.tags))
        # Calculate the file size.
        bytes = len(self.data)
        if bytes >= 1024 * 1024:
            self.size = "%.1f MB" % (float(bytes) / (1024 * 1024))
        elif bytes >= 1024:
            self.size = "%d KB" % (bytes // 1024)
        else:
            self.size = "%d Bytes" % bytes
        # Save the entity to datastore.
        is_new = not self.is_saved()
        key = super(MyFile, self).put()
        if is_new:
            logging.info( "New MyFile '%s' inserted to datastore." % self.name )
        else:
            logging.info( "MyFile '%s' updated in datastore." % self.name )
        return key

    def delete(self):
        super(MyFile, self).delete()
        logging.info( "MyFile '%s' deleted from datastore." % self.name )


